package com.mazaiting.generator.controller;

import cn.hutool.core.io.IoUtil;
import com.mazaiting.generator.domain.query.DownloadQuery;
import com.mazaiting.generator.service.IGeneratorService;
import com.mazaiting.web.utils.HttpUtil;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 代码生成
 */
@Controller
@RequestMapping("generator/v1/generator")
@AllArgsConstructor
public class GeneratorController {

    private final IGeneratorService generatorService;

    /**
     * 生成代码（zip压缩包）
     * @param downloadQuery 下载查询参数
     */
    @GetMapping("download")
    public void download(@Valid DownloadQuery downloadQuery, HttpServletResponse response) throws Exception {
        // 压缩包名
        String fileName = "generator";
        // zip压缩包数据
        byte[] data = generatorService.download(downloadQuery, fileName);
        response.reset();
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        // 设置下载属性
        HttpUtil.setDownloadProp(response, fileName + ".zip", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 输出
        IoUtil.write(response.getOutputStream(), true, data);
    }


//
//    /**
//     * 生成代码（自定义目录）
//     */
//    @ResponseBody
//    @PostMapping("code")
//    public Result<String> code(@RequestBody Long[] tableIds) throws Exception {
//        // 生成代码
//        for (Long tableId : tableIds) {
//            generatorService.generatorCode(tableId);
//        }
//
//        return Result.ok();
//    }

}